package org.numb.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.numb.common.i18n.MessageProcessor;
import org.numb.model.User;
import org.numb.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
@Validated
public class UserController {

    @Resource
    private MessageProcessor messageProcessor;

    @Resource
    private UserService userService;

    @RequestMapping(value = "/user/{user_id}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.OK)
    public User getUser(
        @PathVariable(value = "user_id") @Length(max = 64) @Pattern(regexp = "^[a-z0-9A-Z_-]*$") String id,
        @RequestAttribute(value = "token") String tokenInfo) {
        System.out.println(tokenInfo);
        return userService.getUser(id);
    }

    @RequestMapping(value = "/users", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.ACCEPTED)
    public String getUser(@RequestBody @Valid User users) {
        System.out.println(users);
        return "success";
    }

    @RequestMapping(value = "/user/{user_id}", method = RequestMethod.DELETE, consumes =
        MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.OK)
    public String deleteUser(HttpServletRequest request, HttpServletResponse response,
        @PathVariable(value = "user_id") String userId) {
        String userName = userService.getUserName(userId);
        if (userName == null) {
            throw new NullPointerException();
            // return messageProcessor.getMessage(request, "response.400.message.0002", "userId");
        }
        // delete user
        return "success";
    }

}

